package com.gupao.rpc.protocol.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty服务端
 *
 * @author SuperWein
 */
@Slf4j
public class NettyServer {
    /**
     * 主机
     */
    private final String host;
    /**
     * 端口号
     */
    private final int port;

    public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        log.info("Start netty server...");
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer());
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
            log.info("Netty server started Success on port: {}", this.port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
